package com.ruoyi.file.controller;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.OssException;
import com.ruoyi.file.entity.UploadResult;
import com.ruoyi.file.factory.OssFactory;
import com.ruoyi.file.service.ICloudStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author lsy
 * @Description:
 * @date 2021/8/30
 */
@RestController
@Slf4j
@RequestMapping("oss")
public class OssFileController {


    @PostMapping("/upload")
    public R<?> upload(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new OssException("上传文件不能为空");
        }
        ICloudStorageService storage = OssFactory.instance();
        UploadResult uploadResult;
        String originalfileName = file.getOriginalFilename();
        String suffix = StrUtil.sub(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new OssException("文件读取异常!!!");
        }
        return R.ok(uploadResult);
    }
}
